package frontend.search.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import backend.attribute.manager.AttributeManager;

import core.attribute.model.Attribute;
import core.product.model.Product;
import core.product.model.ProductType;
import core.util.HibernateCoreUtil;
import core.util.database.index.model.ProductSearchIndex;

public class SearchManager  extends HibernateCoreUtil
{
	public List<Product> getSimpleSearchResult(String searchkey)
	{
		List<Product> lstProd = new ArrayList<Product>();
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		ProductSearchIndex psi = null ;
		try 
		{
				transaction = session.beginTransaction();
				//from Category c where c.name='"+name+"' and c.path='"+path+"'")
				Iterator<ProductSearchIndex> psiItr = session.createQuery("from ProductSearchIndex psi where psi.searchKey like '%"+searchkey+"%'").list().iterator();
				while(psiItr.hasNext())
				{
					psi = psiItr.next() ;
					lstProd.add(psi.getResult());
				}
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return lstProd;
	}
	
	public Map<String,Integer> getSuggestionSearch(String searchkey)
	{
		String query = "select name , count(cp.product_uuid) count from category c , category_product cp where c.uuid = cp.category_uuid and c.name like '"+searchkey+"%' group by c.uuid" ;
		Map<String,Integer> suggetionMap = new HashMap<String,Integer>();
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		session.beginTransaction();
		SQLQuery SQLQry = session.createSQLQuery(query).addScalar("name",Hibernate.STRING).addScalar("count", Hibernate.INTEGER);
		Iterator lst = SQLQry.list().iterator();
		while(lst.hasNext())
		{
			Object[] obj = (Object[]) lst.next();
			suggetionMap.put(((String)obj[0]), ((Integer)obj[1]));
		}
		session.getTransaction().commit();
		return suggetionMap ;
	}
	
	public Map<String,Integer> getManagerCount(String qryPart)
	{
		Map<String,Integer> ownerFilter = new HashMap<String,Integer>();
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		session.beginTransaction();
		String managerQry = "select count(*) count , managedby from productowner where product_uuid in " +qryPart+ " group by managedby" ;
		SQLQuery query = session.createSQLQuery(managerQry).addScalar("count", Hibernate.INTEGER).addScalar("managedby",Hibernate.STRING);
		Iterator lst = query.list().iterator();
		while(lst.hasNext())
		{
			Object[] obj = (Object[]) lst.next();
			ownerFilter.put(((String)obj[1]), ((Integer)obj[0]));
		}
		session.getTransaction().commit();
		return  ownerFilter  ;
	}
	
	public String getQueryPart(List<Product> prodLst)
	{
		String qryPart = new String("(");
		Iterator<Product> prodItr = prodLst.iterator();
		while(prodItr.hasNext())
		{
			qryPart = qryPart + prodItr.next().getUuid() + ",";
			
		}
		qryPart = qryPart + "0)";
		return qryPart;
	}
	public String getQueryPartFromId(List<Long> prodLst)
	{
		String qryPart = new String("(");
		Iterator<Long> prodItr = prodLst.iterator();
		while(prodItr.hasNext())
		{
			qryPart = qryPart + prodItr.next() + ",";
			
		}
		qryPart = qryPart + "0)";
		return qryPart;
	}
	public Map<Attribute,Integer> getAttributeFilter(String qryPart,String attributeSet)
	{
		AttributeManager am = new AttributeManager();
		Map<Attribute,Integer> filterIdx = new HashMap<Attribute,Integer>();
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		String tableName = attributeSet + "_filter_index";
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				SQLQuery query = session.createSQLQuery("select attribute_uuid from attributeset aset , attributeset_attribute  asa where aset.uuid = asa.attributeset_uuid and aset.name = '"+attributeSet+"'").addScalar("attribute_uuid", Hibernate.LONG);
				List<Long> attrsLst = query.list();
				Iterator<Long> attrsItr = attrsLst.iterator();
				while(attrsItr.hasNext())
				{
					int count = 0 ;
					Long attrId = attrsItr.next();
					String cols = "c" + attrId;
					Attribute a = am.getAttributeByUuid(attrId);
					String featchCount = "select count(*) count from "+tableName+" where " + cols + " = 1 and productid in " + qryPart ;
					query = session.createSQLQuery(featchCount).addScalar("count",Hibernate.INTEGER);
					List<Integer> countLst =  query.list();
					if(countLst.size() > 0)
					{
						count = countLst.get(0);
					}
					filterIdx.put(a,count);
				}
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return filterIdx ;	
	}
	public List<Long> applyFilter(String sql)
	{
		List<Long> pl = new ArrayList<Long>();
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				SQLQuery query = session.createSQLQuery(sql).addScalar("productid", Hibernate.LONG);
				pl = (List<Long>) query.list();
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return pl;
	}
	public Map<ProductType,Integer> getProductTypeCountMap(String qryPart)
	{
		Map <ProductType,Integer> prodTypeCount  = new HashMap<ProductType, Integer>();
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		List<ProductType> ptyplst = new ArrayList<ProductType>();
		try 
		{
				transaction = session.beginTransaction();
				ptyplst = session.createQuery("from ProductType").list();
				Iterator<ProductType> ptypeItr = ptyplst.iterator();
				while(ptypeItr.hasNext())
				{
					ProductType pt = ptypeItr.next();
					String colName = "c" + pt.getUuid();
					String featchCount = "select count(*) count from product_type_index where " + colName + " = 1 and productid in " + qryPart ;
					SQLQuery cntQry = session.createSQLQuery(featchCount).addScalar("count", Hibernate.INTEGER);
					int cnt = (Integer) cntQry.list().get(0);
					prodTypeCount.put(pt, cnt);
				}
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return prodTypeCount;
	}
	
}
